package com.youi.web;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.youi.common.Common;
import com.youi.common.DelStatus;
import com.youi.common.SessionKey;
import com.youi.entity.Refundorder;
import com.youi.entity.Sysuser;
import com.youi.entity.User;
import com.youi.entity.Userorder;
import com.youi.entity.Yibaodivide;
import com.youi.entity.Yibaopayment;
import com.youi.entity.Yibaorefund;
import com.youi.entity.vo.ExportMerchantOrderVO;
import com.youi.entity.vo.ExportOrderVO;
import com.youi.entity.vo.UserorderexcelVo;
import com.youi.exception.BusinessException;
import com.youi.manage.HttpRequestManage;
import com.youi.manage.HttpSessionManage;
import com.youi.model.WithdrawUserorderstats;
import com.youi.service.GoodsService;
import com.youi.service.GoodssizeService;
import com.youi.service.LeaderprofitService;
import com.youi.service.LeaderprofitdetailService;
import com.youi.service.OrderaftersaleService;
import com.youi.service.OrdergoodsService;
import com.youi.service.OrderprofitdetailService;
import com.youi.service.RefundorderService;
import com.youi.service.UserService;
import com.youi.service.UserorderService;
import com.youi.service.UserorderexcelVoService;
import com.youi.service.WithdrawUserorderstatsService;
import com.youi.service.YibaodivideService;
import com.youi.service.YibaopaymentService;
import com.youi.service.YibaorefundService;
import com.youi.service.impl.AsyncExcelService;
import com.youi.service.impl.TransactionalUserorderService;
import com.youi.third.kuaidi100.ExpressResult;
import com.youi.third.kuaidi100.ExpressUtil;
import com.youi.third.yibaopay.YibaopayUtil;
import com.youi.third.yibaopay.model.Divideresult;
import com.youi.third.yibaopay.model.Refundresult;
import com.youi.util.CommonInfoUtil;
import com.youi.util.DateUtil;
import com.youi.util.EasyPoiUtil;
import com.youi.util.ExcelStyleUtil;
import com.youi.util.JsonUtil;
import com.youi.util.ObjectUtil;
import com.youi.util.Page;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * 用户订单信息控制层
 *
 * @author Administrator
 */
@Controller
public class UserorderController extends HttpRequestManage implements ApplicationContextAware {

    @Autowired
    private UserorderService userorderService;
    @Autowired
    private OrderaftersaleService orderaftersaleService;
    @Autowired
    private OrderprofitdetailService orderprofitdetailService;
    @Autowired
    private LeaderprofitService leaderprofitService;
    @Autowired
    private LeaderprofitdetailService leaderprofitdetailService;
    @Autowired
    private YibaopaymentService yibaopaymentService;
    @Autowired
    private GoodssizeService goodssizeService;
    @Autowired
    private YibaorefundService yibaorefundService;
    @Autowired
    private RefundorderService refundorderService;
    @Autowired
    private OrdergoodsService ordergoodsService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private UserService userService;
    @Autowired
    private YibaodivideService yibaodivideService;
    @Autowired
    private WithdrawUserorderstatsService withdrawUserorderstatsService;
    @Autowired
    private UserorderexcelVoService userorderexcelService;
    @Autowired
    private AsyncExcelService asyncExcelService;
    @Autowired
    private TransactionalUserorderService transactionalUserorderService;


    /**
     * 同步静态对象 零长度的byte数组对象创建起来将比任何对象都经济――查看编译后的字节码：生成零长度的byte[]对象只需3条操作码，而Object lock = new Object()则需要7行操作码
     */
    private static byte[] lock = null;

    /**
     * I-30
     * 查询用户订单信息列表
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/getUserorder")
    public String getUserOrder(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        //获取查询参数
        Integer pageIndex = optInteger("pageIndex", request, 1);
        Integer pageNum = optInteger("pageNum", request, 10);
        Integer status = optInteger(Common.STATUS, request);
        String topOrderNo = optString("topOrderNo", request);
        String goodsNo = optString("goodsNo", request);
        String pms = optString("pms", request);
        String merchantName = optString("merchantName", request);
        String otherpms = optString("otherpms", request);
        String start = optString("start", request);
        String end = optString("end", request);
        String des = optString("des", request, Common.DESC);

        //匹配查询
        Map<String, Object> params = Maps.newHashMap();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
        if (sysuser.getMerchantId() != null) {
            params.put("merchantId", sysuser.getMerchantId());
        }
        if (status != null) {
            params.put(Common.STATUS, status);
        }
        //主订单号
        if (StringUtils.isNotBlank(topOrderNo)) {
            params.put("topOrderNo", topOrderNo);
        }
        //商品编号
        if (StringUtils.isNotBlank(goodsNo)) {
            List<Long> orderIds = ordergoodsService.getOrderIds(goodsNo);
            List<Long> orderIdList = ObjectUtil.removeDuplicate(orderIds);
            if (orderIdList == null || orderIdList.size() == 0) {
                return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "相关商品编码订单不存在");
            }
            params.put("id", orderIdList);
        }
        /*
        if (topOrderNo != null && topOrderNo.length() > 0) {
            String orderNos = userorderService.getUserorderByTopOrderNo(topOrderNo);
            List<String> orderNoList = ObjectUtil.getStringListByIds(orderNos);
            if (orderNoList != null && orderNoList.size() > 0) {
                params.put("orderNo", orderNoList);
            } else {
                params.put("orderNo", "0");
            }
        }*/

        //订单号和收货人模糊查询
        Map<String, Object> searchPram = null;
        if (StringUtils.isNotBlank(pms)) {
            searchPram = Maps.newHashMap();
            searchPram.put("orderNo", pms);
            searchPram.put("consignee", pms);
        }
        //收货电话和快递单号
        Map<String, Object> otherParams = null;
        if (otherpms != null && otherpms.length() > 0) {
            otherParams = Maps.newHashMap();
            otherParams.put("phone", otherpms);
            otherParams.put("expressNo", otherpms);
        }
        //商家名称和编码模糊查询(商家端不需要)
        Map<String, Object> merchantParams = null;
        if (StringUtils.isNotBlank(merchantName)) {
            merchantParams = Maps.newHashMap();
            merchantParams.put("merchantName", merchantName);
            merchantParams.put("merchantCode", merchantName);
        }
        //下单时间
        Map<String, Object> startTimeMap = null;
        if (StringUtils.isNotBlank(start)) {
            startTimeMap = Maps.newHashMap();
            startTimeMap.put("gmtOrder", DateUtil.simpdfyMdHms.parse(start));
        }
        Map<String, Object> endTimeMap = null;
        if (StringUtils.isNotBlank(end)) {
            endTimeMap = Maps.newHashMap();
            endTimeMap.put("gmtOrder", DateUtil.simpdfyMdHms.parse(end));
        }

        Map<String, Object> sortPram = Maps.newHashMap();
        sortPram.put(Common.ID, des);

        List<Userorder> userOrderList = userorderService.getUserorderList(params, searchPram, otherParams, merchantParams, sortPram,
                (pageIndex - 1) * pageNum, pageNum, startTimeMap, endTimeMap);
        if (CollectionUtils.isEmpty(userOrderList)) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        Integer pageCount = userorderService.getUserorderCount(params, searchPram, otherParams, merchantParams, startTimeMap, endTimeMap);
        modelMap.put(CommonInfoUtil.PAGECOUNT, Page.getCount(pageCount, pageNum));
        modelMap.put(CommonInfoUtil.PAGEINDEX, pageIndex);
        modelMap.put(CommonInfoUtil.ALLCOUINT, pageCount);
        modelMap.put(CommonInfoUtil.DATA, userOrderList);
        userorderService.getUserordermsg(userOrderList);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", modelMap);
    }

    /**
     * 导出订单
     *
     * @param param
     * @param request
     * @param response
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/exportOrder", produces = "application/json")
    public void exportOrder(@RequestBody Map<String, Object> param, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //查询订单数据,根据条件查询全部数据,不分页
        List<ExportOrderVO> exportOrderList = userorderService.listExportOrderByParam(param);
        if (CollectionUtils.isEmpty(exportOrderList)) {
            throw new BusinessException(-1, "没有要导出的数据");
        }

        try {
            String fileName = "订单" + DateUtil.simpyMdHHmmss.format(new Date());
            ExportParams exportParams = new ExportParams(null, "订单", ExcelType.XSSF);
            exportParams.setStyle(ExcelStyleUtil.class);

            EasyPoiUtil.exportExcel(fileName, exportParams, ExportOrderVO.class, exportOrderList, request, response);
        } catch (Exception ex) {
            throw new BusinessException(-1, "导出数据失败");
        }
    }

    /**
     * I-31
     * 查询用户订单信息详情
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/getUserorderById")
    public String getUserorderById(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        Long id = getLong("id", request);
        Userorder userorder = userorderService.get(id);
        if (userorder == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        userorderService.getUserordermsg(userorder);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", userorder);//jsonObject	json对象
    }

    /**
     * I-32
     * 查询订单物流信息
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/getUserorderExpressMsg")
    public String getUserorderExpressMsg(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        Long id = getLong("id", request);
        Userorder userorder = userorderService.get(id);
        if (userorder == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        String result = ExpressUtil.getExpressMsg(ObjectUtil.removeAllBlank(userorder.getExpressCode()), ObjectUtil.removeAllBlank(userorder.getExpressNo()), ObjectUtil.removeAllBlank(userorder.getPhone()), null, null, 0);
        if (result == null || result.length() == 0) {
            JsonUtil.toJson(CommonInfoUtil.PARAMERROR, "查询失败");
        }
        ExpressResult expressResult = JsonUtil.fromJson(result, ExpressResult.class);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", expressResult);//jsonObject	json对象
    }

    /**
     * I-33-1
     * 批量订单发货
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/deliverUservipByIds")
    public String deliverUservipByIds(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        String ids = getString("ids", request);
        String express = optString("express", request);
        String expressCode = optString("expressCode", request);
        String expressNo = optString("expressNo", request);
        List<Long> idsList = ObjectUtil.getIdListByIds(ids);
        if (idsList == null || idsList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.PARAMERROR, "ids参数错误");
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        params.put(Common.ID, idsList);
        List<Userorder> userorderList = userorderService.getByParams(params);
        if (userorderList == null || userorderList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        for (Userorder userorder : userorderList) {
            userorder.setStatus(2);
            if (express != null && express.trim().length() > 0) {
                userorder.setExpress(express.trim());
            }
            if (expressCode != null && express.trim().length() > 0) {
                userorder.setExpressCode(expressCode.trim());
            }
            if (expressNo != null && expressNo.trim().length() > 0) {
                userorder.setExpressNo(expressNo.trim());
            }
            userorder.setShipmentStatus(1);
            userorder.setGmtDelivery(new Date());
            userorder.setGmtShipment(new Date());
        }
        userorderService.saveOrUpdateAll(userorderList);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");//jsonObject	json对象
    }

    /**
     * I-33
     * 订单发货
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/deliverUserorderById")
    public String deliverUserorderById(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        Long id = getLong("id", request);
        String express = optString("express", request);
        String expressCode = optString("expressCode", request);
        String expressNo = optString("expressNo", request);
        Userorder userorder = userorderService.get(id);
        if (userorder == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        userorder.setStatus(2);
        if (express != null && express.trim().length() > 0) {
            userorder.setExpress(express.trim());
        }
        if (expressCode != null && express.trim().length() > 0) {
            userorder.setExpressCode(expressCode.trim());
        }
        if (expressNo != null && expressNo.trim().length() > 0) {
            userorder.setExpressNo(expressNo.trim());
        }
        userorder.setShipmentStatus(1);
        userorder.setGmtShipment(new Date());
        userorder.setGmtDelivery(new Date());
        userorderService.saveOrUpdate(userorder);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");//jsonObject	json对象
    }

    /**
     * I-63
     * 批量导入快递信息发货
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/bathImprotUserorder")
    public String bathImprotUserorder(ModelMap modelMap, HttpServletRequest request, @RequestParam(value = "info_file") MultipartFile files) throws BusinessException {
        try {
            Workbook book = null;
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            CommonsMultipartFile multipartFile = (CommonsMultipartFile) multipartRequest.getFile("info_file");
            userorderService.improtExpressExcel(multipartFile, book);
        } catch (BiffException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return JsonUtil.toJson(CommonInfoUtil.PARAMERROR, "导入失败请检查excel文件");
        }
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");//jsonObject	json对象
    }

    /**
     * I-66
     * 处理用户订单售后
     *
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/disposeOrderafterById")
    public String disposeOrderafterById(ModelMap modelMap, HttpServletRequest request) throws BusinessException, IOException {
        String ids = getString("ids", request);
        Integer refund = getInteger(Common.STATUS, request);//(-2已拒绝 -1非售后 0申请中 1已处理 2已退款)
        List<Long> idsList = ObjectUtil.getIdListByIds(ids);
        if (idsList == null || idsList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.PARAMERROR, "ids参数错误");
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        params.put(Common.ID, idsList);
        List<Userorder> userorderList = userorderService.getByParams(params);
        for (Userorder userorder : userorderList) {
            if (userorder.getMerchantStatus() == 1 || userorder.getPlatformStatus() == 1) {
                return JsonUtil.toJson(CommonInfoUtil.NOOPPMS, "订单处于可提现状态无法退款");
            }
            Map<String, Object> prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            prams.put("orderId", userorder.getOrderNo());
            Refundorder refundorder = refundorderService.getByParam(prams);
            if (refundorder == null) {
                return JsonUtil.toJson(CommonInfoUtil.NULLOBJECT, "退款订单不存在或已被删除");
            }
            prams = new HashMap<String, Object>();
            prams.put(Common.DELSTATUS, DelStatus.NODEL);
            Map<String, Object> searchParams = new HashMap<String, Object>();
            searchParams.put("orderNos", userorder.getOrderNo());
            Yibaopayment yibaopayment = yibaopaymentService.getByParam(prams, searchParams, null);
            if (yibaopayment == null) {
                return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "订单流水信息不存在");
            }
            if (refund == 2) {
                Yibaodivide yibaodivide = null;
                Divideresult divideresult = YibaopayUtil.yibaoDivide(yibaopayment, userorder);
                if (divideresult == null || !divideresult.getCode().equals("OPR00000")) {
                    prams = new HashMap<String, Object>();
                    prams.put(Common.DELSTATUS, DelStatus.NODEL);
                    prams.put("orderNo", userorder.getOrderNo());
                    yibaodivide = yibaodivideService.getByParam(prams);
                    if (yibaodivide == null) {
                        yibaodivide = new Yibaodivide(divideresult.getStatus(), divideresult.getOrderId(), userorder.getOrderNo(), divideresult.getUniqueOrderNo(),
                                divideresult.getDivideRequestId(), divideresult.getDivideDetail());
                        yibaodivideService.saveOrUpdate(yibaodivide);
                    }
                    JSONObject jsonObject = YibaopayUtil.getYibaoDivide(yibaodivide.getOrderId(), yibaodivide.getUniqueOrderNo(), yibaodivide.getDivideRequestId());
                    if (jsonObject != null && !jsonObject.getString("code").equals("OPR00000")) {
                        return JsonUtil.toJson(CommonInfoUtil.DATAERROR, divideresult.getCode(), divideresult);
                    }
                } else {
                    yibaodivide = new Yibaodivide(divideresult.getStatus(), divideresult.getOrderId(), userorder.getOrderNo(), divideresult.getUniqueOrderNo(),
                            divideresult.getDivideRequestId(), divideresult.getDivideDetail());
                    yibaodivideService.saveOrUpdate(yibaodivide);
                }
                Refundresult refundresult = YibaopayUtil.yibaoRefund(yibaodivide, userorder, yibaopayment);
                if (refundresult == null || !refundresult.getCode().equals("CAS00000")) {
                    return JsonUtil.toJson(CommonInfoUtil.DATAERROR, "易宝退款接口调用失败", refundresult);
                }
            } else if (refund == 1) {
                refundorder.setStatus(1);
                userorder.setRefund(1);
            }
            userorder.setGmtModify(new Date());
            refundorderService.saveOrUpdate(refundorder);
            userorderService.saveOrUpdate(userorder);
        }

        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");//jsonObject	json对象
    }

    /**
     * I-87
     * 修改订单快递信息
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/updateUserorderExpressNo")
    public String updateUserorderExpressNo(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        Long id = getLong(Common.ID, request);
        String express = optString("express", request);
        String expressNo = optString("expressNo", request);
        String expressCode = optString("expressCode", request);
        Userorder userorder = userorderService.get(id);
        if (userorder == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        if (express != null && express.length() > 0) {
            userorder.setExpress(express);
        }
        if (expressNo != null && expressNo.length() > 0) {
            userorder.setExpressNo(expressNo);
        }
        if (expressCode != null && expressCode.length() > 0) {
            userorder.setExpressCode(expressCode);
        }
        userorder.setGmtModify(new Date());
        userorderService.saveOrUpdate(userorder);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
    }

    /**
     * I-65
     * 导出excel
     *
     * @param modelMap
     * @param session
     * @return
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping("tocreatedExcelUserorder")
    public String getAllUserorder(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
        Integer status = optInteger(Common.STATUS, request);
        String pms = optString("pms", request);
        String merchantName = optString("merchantName", request);
        String otherpms = optString("otherpms", request);
        String topOrderNo = optString("topOrderNo", request);
        String goodsNo = optString("goodsNo", request);
        String start = optString("start", request);
        String end = optString("end", request);
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        Long merchantId = null;
        if (sysuser.getMerchantId() != null) {
            merchantId = sysuser.getMerchantId();
        }
        //主订单号
        String orderNos = null;
        if (topOrderNo != null && topOrderNo.length() > 0) {
            String orderNoList = userorderService.getUserorderByTopOrderNo(topOrderNo);
            if (orderNoList != null && orderNoList.length() > 0) {
                orderNos = orderNoList;
            }
        }
        List<UserorderexcelVo> userorderexcelList = userorderexcelService.getUserorderexcelList(merchantId, status, orderNos, pms, merchantName, goodsNo, otherpms, start, end);
        if (userorderexcelList == null || userorderexcelList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        userorderexcelService.getTopOrderNo(userorderexcelList);
        userorderService.tocreatedExcel(request, userorderexcelList);
        modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.SUCCESS);
        modelMap.put(CommonInfoUtil.JSONMSG, "操作成功");
        return JsonUtil.toJson(modelMap);//jsonObjectList	json对象集合
    }


    /**
     * I-88
     * 下载快递单号模板
     */
    @ResponseBody
    @RequestMapping("downloadExpressNo")
    public String downloadExpressNo(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
        Integer status = optInteger(Common.STATUS, request);
        String des = optString("des", request, Common.DESC);
        String pms = optString("pms", request);
        String topOrderNo = optString("topOrderNo", request);
        String goodsNo = optString("goodsNo", request);
        String merchantName = optString("merchantName", request);
        String otherpms = optString("otherpms", request);
        String start = optString("start", request);
        String end = optString("end", request);
        String ids = optString("ids", request);
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        if (sysuser.getMerchantId() != null) {
            prams.put("merchantId", sysuser.getMerchantId());
        }
        if (ids != null && ids.length() > 0) {
            List<Long> idList = ObjectUtil.getIdListByIds(ids);
            if (idList != null && idList.size() > 0) {
                prams.put(Common.ID, idList);
            }
        }
        if (status != null) {
            prams.put(Common.STATUS, status);
        }
        //主订单号
        if (topOrderNo != null && topOrderNo.length() > 0) {
            String orderNos = userorderService.getUserorderByTopOrderNo(topOrderNo);
            if (orderNos != null && orderNos.length() > 0) {
                prams.put("orderNo", Arrays.asList(orderNos));
            } else {
                prams.put("orderNo", "0");
            }
        }
        //商品编码
        if (goodsNo != null && goodsNo.length() > 0) {
            List<Long> orderIds = ordergoodsService.getOrderIds(goodsNo);
            List<Long> orderIdList = ObjectUtil.removeDuplicate(orderIds);
            if (orderIdList == null || orderIdList.size() == 0) {
                return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "相关商品编码订单不存在");
            }
            prams.put("id", orderIdList);
        }
        Map<String, Object> sortPram = new HashMap<String, Object>();
        sortPram.put(Common.ID, des);
        //订单号和收货人
        Map<String, Object> searchPram = null;
        if (pms != null && pms.length() > 0) {
            searchPram = new HashMap<String, Object>();
            searchPram.put("orderNo", pms);
            searchPram.put("consignee", pms);
        }
        //商家名称(商家端不需要)
        Map<String, Object> merchantParams = null;
        if (merchantName != null && merchantName.length() > 0) {
            merchantParams = new HashMap<String, Object>();
            merchantParams.put("merchantName", merchantName);
            merchantParams.put("merchantCode", merchantName);
        }
        //收货电话和快递单号
        Map<String, Object> otherParams = null;
        if (otherpms != null && otherpms.length() > 0) {
            otherParams = new HashMap<String, Object>();
            otherParams.put("phone", otherpms);
            otherParams.put("expressNo", otherpms);
        }
        Map<String, Object> startTime = null;
        if (start != null) {
            startTime = new HashMap<String, Object>();
            startTime.put("gmtOrder", DateUtil.simpdfyMdHms.parse(start + " 00:00:00"));
        }
        Map<String, Object> endTime = null;
        if (end != null) {
            endTime = new HashMap<String, Object>();
            endTime.put("gmtOrder", DateUtil.simpdfyMdHms.parse(end + " 23:59:59"));
        }
        List<Userorder> userorderList = userorderService.getAllUserorderList(prams, searchPram, otherParams, merchantParams, sortPram, startTime, endTime);
        if (userorderList == null || userorderList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        modelMap.put("url", userorderService.toExpressExcel(request, userorderList));
        modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.SUCCESS);
        modelMap.put(CommonInfoUtil.JSONMSG, "操作成功");
        return JsonUtil.toJson(modelMap);
    }

    /**
     * I-87
     * 后台订单直接退款
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/sysRefundUserorder")
    public String sysRefundUserorder(ModelMap modelMap, HttpServletRequest request) throws BusinessException, IOException {
        String orderNo = getString("orderNo", request);
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        Map<String, Object> searchParams = new HashMap<String, Object>();
        searchParams.put("orderNos", orderNo);
        Yibaopayment yibaopayment = yibaopaymentService.getByParam(prams, searchParams, null);
        if (yibaopayment == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "订单流水信息不存在");
        }
        prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("orderNo", orderNo);
        Userorder userorder = userorderService.getByParam(prams);
        if (userorder == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "订单不存在");
        }
        if (userorder.getStatus() != 1) {
            return JsonUtil.toJson(CommonInfoUtil.NOPERMISSIONS, "订单不是待发货装态无法退款");
        }
        if (userorder.getStatus() >= 2) {
            return JsonUtil.toJson(CommonInfoUtil.NOPERMISSIONS, "订单已发货无法退款");
        }
        prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put(Common.ID, userorder.getId());
        User user = userService.getByParam(prams);
        if (user == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "用户不存在");
        }
        prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("orderNo", orderNo);
        Yibaodivide yibaodivide = yibaodivideService.getByParam(prams);
        if (yibaodivide == null) {
            Divideresult divideresult = YibaopayUtil.yibaoDivide(yibaopayment, userorder);
            if (divideresult != null && divideresult.getCode().equals("OPR00000")) {
                yibaodivide = new Yibaodivide(divideresult.getStatus(), divideresult.getOrderId(), orderNo, divideresult.getUniqueOrderNo(),
                        divideresult.getDivideRequestId(), divideresult.getDivideDetail());
                yibaodivideService.saveOrUpdate(yibaodivide);
            } else {
                return JsonUtil.toJson(CommonInfoUtil.DATAERROR, divideresult.getMessage(), divideresult);
            }
        } else {
            JSONObject jsonObject = YibaopayUtil.getYibaoDivide(yibaodivide.getOrderId(), yibaodivide.getUniqueOrderNo(), yibaodivide.getDivideRequestId());
            if (jsonObject != null && !jsonObject.getString("code").equals("OPR00000")) {
                return JsonUtil.toJson(CommonInfoUtil.DATAERROR, jsonObject.getString("message"), jsonObject);
            }
        }
        prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put("orderNo", orderNo);
        Yibaorefund yibaorefund = yibaorefundService.getByParam(prams);
        if (yibaorefund == null) {
            Refundresult refundresult = YibaopayUtil.yibaoRefund(yibaodivide, userorder, yibaopayment);
            if (refundresult != null && refundresult.getCode().equals("OPR00000")) {
                String refundOrderNo = "3" + new Date().getTime() + user.getId().toString();
                refundorderService.saveOrUpdate(new Refundorder(user, 0, refundOrderNo, userorder));
                yibaorefund = new Yibaorefund(refundresult, yibaopayment, userorder.getOrderNo());
                yibaorefundService.saveOrUpdate(yibaorefund);
            } else {
                JSONObject data = YibaopayUtil.yibaoGetRefund(yibaorefund.getOrderId(), yibaorefund.getUniqueRefundNo(), yibaorefund.getRefundOrderNo());
                if (data != null && !data.getString("code").equals("OPR00000")) {
                    return JsonUtil.toJson(CommonInfoUtil.DATAERROR, data.getString("message"), data);
                }
            }
        }
        transactionalUserorderService.cancelOrdergoods(userorder, true);
//			prams=new HashMap<String, Object>();
//			prams.put(Common.DELSTATUS, DelStatus.NODEL);
//			prams.put("orderId", userorder.getId());
//			List<Ordergoods> ordergoodsList=ordergoodsService.getByParams(prams);
//			if (ordergoodsList!=null&&ordergoodsList.size()>0) {
//				for (Ordergoods ordergoods : ordergoodsList) {
//					prams=new HashMap<String, Object>();
//					prams.put(Common.DELSTATUS, DelStatus.NODEL);
//					prams.put("goodsId", ordergoods.getGoodsId());
//					prams.put("specification", ordergoods.getSpecification());
//					prams.put("price", ordergoods.getSlaePrice());
//					Goodssize goodssize=goodssizeService.getByParam(prams);
//					if (goodssize!=null) {
//						Goods goods=goodsService.get(goodssize.getGoodsId());
//						if (goods!=null) {
//							Goodssize redisGoodssize=JedisUtils.getObject(goodssize.getId().toString(), Goodssize.class);
//							if (redisGoodssize==null) {
//								goodssize.setAllStockNum(goods.getAllStockNum());
//								goodssize.setRealStockCnt(goods.getRealStockCnt());
//								goodssize.setRealSaleCnt(goods.getRealSaleCnt());
//								JedisUtils.setObject(goodssize.getId().toString(), goodssize);
//								redisGoodssize=JedisUtils.getObject(goodssize.getId().toString(), Goodssize.class);
//							}
//							redisGoodssize.setRealStockNum(redisGoodssize.getRealStockNum()+ordergoods.getCount());
//							redisGoodssize.setSaleNum(redisGoodssize.getSaleNum()-ordergoods.getCount());
//							redisGoodssize.setRealSaleCnt(redisGoodssize.getRealSaleCnt()-ordergoods.getCount());
//							if (redisGoodssize.getRealSaleCnt()<=0) {
//								goods.setRealSaleCnt(0);									
//							}
////							if (goods.getRealSaleCnt()>0) {
////								goods.setRealSaleCnt(goods.getRealSaleCnt()-ordergoods.getCount());	
////							}
//							if (redisGoodssize.getRealSaleCnt()<=redisGoodssize.getAllStockNum()) {
//								goods.setStatus(1);									
//							}
//							goods.setRealSaleCnt(redisGoodssize.getRealSaleCnt());
//							goodssizeService.saveOrUpdate(redisGoodssize);
//							goodsService.saveOrUpdate(goods);
//							JedisUtils.setObject(goodssize.getId().toString(), redisGoodssize);
//						}
//					}					
//				}			
//			}
//			userorder.setStatus(-1);
//			userorder.setRefund(1);
//			userorderService.saveOrUpdate(userorder);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", modelMap);
    }


    /**
     * I-89
     * 查询供应商打款申请单列表
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/getWithdrawUserorder")
    public String getWithdrawUserOrder(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        Integer pageIndex = optInteger("pageIndex", request, 1);
        Integer pageNum = optInteger("pageNum", request, 10);
        //查询参数
        String topOrderNo = optString("topOrderNo", request);
        String orderNo = optString("orderNo", request);
        String start = optString("start", request);
        String end = optString("end", request);
        String pms = optString("pms", request);
        Integer status = optInteger(Common.STATUS, request);
        String des = optString("des", request, Common.DESC);

        Map<String, Object> prams = Maps.newHashMap();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put(Common.STATUS, Arrays.asList(1, 2, 3, 4, 5));
        prams.put("refund", -1);
        Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
        if (sysuser.getMerchantId() != null) {
            prams.put("merchantId", sysuser.getMerchantId());
        }
        if (StringUtils.isNotBlank(topOrderNo)) {
            prams.put("topOrderNo", topOrderNo);
        }
        if (StringUtils.isNotBlank(orderNo)) {
            prams.put("orderNo", orderNo);
        }
        if (status != null) {
            if (status == 6) {
                prams.put("merchantStatus", Arrays.asList(1, 4));
            } else {
                prams.put("merchantStatus", status);
            }
        }

        Map<String, Object> sortPram = Maps.newHashMap();
        sortPram.put(Common.ID, des);

        //供应商编码/供应商编号
        Map<String, Object> searchPram = null;
        if (StringUtils.isNotBlank(pms)) {
            searchPram = Maps.newHashMap();
            searchPram.put("merchantCode", pms);
            searchPram.put("merchantName", pms);
        }

        Map<String, Object> startTimeMap = null;
        if (start != null) {
            startTimeMap = Maps.newHashMap();
            startTimeMap.put("gmtOrder", DateUtil.simpdfyMdHms.parse(start));
        }
        Map<String, Object> endTimeMap = null;
        if (end != null) {
            endTimeMap = Maps.newHashMap();
            endTimeMap.put("gmtOrder", DateUtil.simpdfyMdHms.parse(end));
        }

        List<Userorder> userOrderList = userorderService.getByParamsList(prams, searchPram, sortPram,
                (pageIndex - 1) * pageNum, pageNum, startTimeMap, endTimeMap);
        if (CollectionUtils.isEmpty(userOrderList)) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        Integer pageCount = userorderService.getCountByParamss(prams, searchPram, startTimeMap, endTimeMap);
        modelMap.put(CommonInfoUtil.PAGECOUNT, Page.getCount(pageCount, pageNum));
        modelMap.put(CommonInfoUtil.PAGEINDEX, pageIndex);
        modelMap.put(CommonInfoUtil.ALLCOUINT, pageCount);
        modelMap.put(CommonInfoUtil.DATA, userOrderList);
        userorderService.getWithdrawUserorderMsg(userOrderList);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", modelMap);
    }

    /**
     * I-90
     * 查询供应商打款申请单详情
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/getWithdrawUserorderById")
    public String getWithdrawUserorderById(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        Long id = getLong("id", request);
        Userorder userorder = userorderService.get(id);
        if (userorder == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        userorderService.getWithdrawUserorderMsg(userorder);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", userorder);//jsonObject	json对象
    }

    /**
     * I-91
     * 查询供应商打款申请单统计数
     *
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping("sysUserGetInfo/getWithdrawUserorderStats")
    public String getWithdrawUserorderStats(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
        Integer status = optInteger(Common.STATUS, request);
        String pms = optString("pms", request);
        String start = optString("start", request);
        String end = optString("end", request);
        String des = optString("des", request, Common.DESC);
        String orderNo = optString("orderNo", request);
        Long merchantId = null;
        if (sysuser.getMerchantId() != null) {
            merchantId = sysuser.getMerchantId();
        }
        WithdrawUserorderstats withdrawUserorderstats = withdrawUserorderstatsService.getUserorderstatByParamss(status, start, end, merchantId, pms, orderNo);
        modelMap.put("merchantCount", withdrawUserorderstats.getMerchantCount());
        modelMap.put("orderCount", withdrawUserorderstats.getOrderCount());
        modelMap.put("orderAmount", withdrawUserorderstats.getOrderAmount());
        modelMap.put("merchantAmount", withdrawUserorderstats.getMerAmount());
        modelMap.put("platformAmount", withdrawUserorderstats.getPlatAmount());
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", modelMap);
    }

    /**
     * I-92
     * 导出供应商提现订单excel
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     * @throws ParseException
     */
    @Deprecated
    @ResponseBody
    @RequestMapping("downloadWithdrawUserorder")
    public String downloadWithdrawUserorder(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
        Integer status = optInteger(Common.STATUS, request);
        String pms = optString("pms", request);
        String start = optString("start", request);
        String end = optString("end", request);
        String des = optString("des", request, Common.DESC);
        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put(Common.STATUS, Arrays.asList(1, 2, 3, 4, 5));
        prams.put("refund", -1);
        if (sysuser.getMerchantId() != null) {
            prams.put("merchantId", sysuser.getMerchantId());
        }
        if (status != null) {
            if (status == 6) {
                prams.put("merchantStatus", Arrays.asList(1, 4));
            } else {
                prams.put("merchantStatus", status);
            }
        }
        Map<String, Object> sortPram = new HashMap<String, Object>();
        sortPram.put(Common.ID, des);
        //供应商编码/供应商编号
        Map<String, Object> searchPram = null;
        if (pms != null && pms.length() > 0) {
            searchPram = new HashMap<String, Object>();
            searchPram.put("merchantCode", pms);
            searchPram.put("merchantName", pms);
        }
        Map<String, Object> startTime = null;
        if (start != null) {
            startTime = new HashMap<String, Object>();
            startTime.put("gmtOrder", DateUtil.simpdfyMdHms.parse(start));
        }
        Map<String, Object> endTime = null;
        if (end != null) {
            endTime = new HashMap<String, Object>();
            endTime.put("gmtOrder", DateUtil.simpdfyMdHms.parse(end));
        }
        List<Userorder> userorderList = userorderService.getByParamsAll(prams, searchPram, sortPram, startTime, endTime);
        userorderService.getWithdrawUserorderMsg(userorderList);
        userorderService.toWithdrawUserorderExcel(request, userorderList);
        modelMap.put(CommonInfoUtil.JSONCODE, CommonInfoUtil.SUCCESS);
        modelMap.put(CommonInfoUtil.JSONMSG, "操作成功");
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", modelMap);
    }


    /**
     * 导出供应商可打款订单
     */
    @ResponseBody
    @RequestMapping(value = "sysUserGetInfo/exportMerchantOrder", produces = "application/json")
    public void exportMerchantOrder(@RequestBody Map<String, Object> param, HttpServletRequest request, HttpServletResponse response) throws BusinessException, ParseException {
        Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
        if (sysuser.getMerchantId() != null) {
            param.put("merchantId", sysuser.getMerchantId());
        }

        List<ExportMerchantOrderVO> exportOrderList = userorderService.listExportMerchantOrder(param);
        if (CollectionUtils.isEmpty(exportOrderList)) {
            throw new BusinessException(-1, "没有要导出的数据");
        }

        try {
            String fileName = "订单" + DateUtil.simpyMdHHmmss.format(new Date());
            ExportParams exportParams = new ExportParams(null, "订单", ExcelType.XSSF);
            exportParams.setStyle(ExcelStyleUtil.class);

            EasyPoiUtil.exportExcel(fileName, exportParams, ExportMerchantOrderVO.class, exportOrderList, request, response);
        } catch (Exception ex) {
            throw new BusinessException(-1, "导出数据失败");
        }
    }

    /**
     * 定时器线程池
     */
    private static ScheduledThreadPoolExecutor executor;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // TODO Auto-generated method stub
        if (lock == null) {
            lock = new byte[0];
            executor = new ScheduledThreadPoolExecutor(1);
        }
    }
}
